// 获取轮播图列表数据
function swiperList() {
  $.ajax({
    url: "/admin/swipers",
    success: function (res) {
      let banner = template("table-tpl", res);
      $(".layui-table tbody").html(banner);
    },
  });
}
// let str = "";
// res.data.forEach((item) => {
//   let span = "";
//   if (item.swiperstatus === 1) {
//     span = `<span data-id='{{$value.id}}' data-status='2' class="layui-badge layui-bg-green">√</span>`;
//   } else {
//     span = `<span data-id='{{$value.id}}' data-status='1' class="layui-badge layui-bg-green">×</span>`;
//   }
//   str += `
//     <tr>
// 		  <td>xxxxxx</td>
//       <td>xxxxxx</td>
//       <td>${span}</td>
//       <td>xxxxxx</td>
// 	  </tr>`;
// });

swiperList();

// 轮播图状态切换
$(".layui-table tbody").on("click", ".layui-badge", function (e) {
  let status = $(e.target).data("status");
  let id = $(e.target).data("id");
  $.ajax({
    type: "PUT",
    url: "/admin/swipers/" + id,
    data: {
      status: status,
    },
    success: function (res) {
      if (res.status === 0) {
        layer.msg(res.message);
        swiperList();
      }
    },
  });
});

// 删除
$(".layui-table tbody").on("click", ".delete", function (e) {
  let id = $(e.target).data("id");
  layer.confirm("真的要删除吗?", function (index) {
    $.ajax({
      type: "DELETE",
      url: "/admin/swipers/" + id,
      success: function (res) {
        if (res.status === 0) {
          layer.close(index);
          swiperList();
        }
      },
    });
  });
});

// 上传轮播图按钮点击事件
$("body").on("click", "#uploadSwiper", function () {
  $("#myfile").click();
});

// 监听文件选中事件
$("body").on("change", "#myfile", function (e) {
  let files = e.target.files;
  let fd = new FormData();
  if (files.length > 0) {
    for (let i = 0; i < files.length; i++) {
      fd.append("swipers", files[i]);
    }
    $.ajax({
      type: "POST",
      url: "/admin/swipers",
      data: fd,
      processData: false,
      contentType: false,
      success: function (res) {
        if (res.status === 0) {
          layer.msg(res.message);
          swiperList();
        }
      },
    });
  }
});
